package com.jasmine.bjstkserver.server.article.log.viewlog;
import com.jasmine.bjstkserver.server.article.online.model.ArticleReq;
import com.jasmine.core.util.SpringContextHolder;
import com.jasmine.core.util.WebUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 文章阅读日志切面
 *
 * @author jasmineXz
 */
@Aspect
@Component
public class ViewLogAspect {
    private static final Logger log = LoggerFactory.getLogger(ViewLogAspect.class);

    @Around("@annotation(viewLog)")
    public Object around(ProceedingJoinPoint point,ViewLog viewLog) throws Throwable {
        Object obj = point.proceed(point.getArgs());
        this.publishEvent(point.getArgs(),viewLog);
        return obj;
    }


    private void publishEvent (Object[] args,ViewLog viewLog) {
        String [] types = viewLog.type();
        ViewLogEntity log = createLog(args);
        if (log != null) {
            SpringContextHolder.publishEvent(new ArticleViewLogEvent(log,types));
        }
    }


    private ViewLogEntity createLog (Object[] args) {
        ArticleReq req = (ArticleReq)args[0];
        if (req.getArticleId() == null) {
            return null;
        }

        HttpServletRequest request =
                ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        ViewLogEntity newLog = new ViewLogEntity();
        newLog.setArticleId(req.getArticleId());
        newLog.setCreTime(LocalDateTime.now());
        newLog.setRemoteAddr(WebUtil.getIP(request));
        newLog.setUserAgent(request.getHeader("user-agent"));
        return newLog;
    }
}
